/**
 * Copyright (c) 2013 onionframework.org
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.onionframework.faces.component;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.event.ValueChangeEvent;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.onionframework.core.config.SystemConfig;
import org.richfaces.component.UISequence;
import org.richfaces.renderkit.util.RendererUtils;
import org.springframework.stereotype.Component;

/**
 * @author allan
 *
 */
@Component("faces.rows")
public class Rows{

	private List<Integer> selections = new ArrayList<Integer>();
	
	@PostConstruct
	public void init(){
		String[] rows = SystemConfig.Config.getStringArray("onion.faces.list.rows");
		if(ArrayUtils.isEmpty(rows)){
			rows = new String[]{"10","20","50","100"};
		}
		
		for(String row : rows)
			selections.add(Integer.valueOf(row));
	}

	public void change(ValueChangeEvent event){
		String target = (String) event.getComponent().getAttributes().get("for");
		UISequence data = (UISequence) RendererUtils.getInstance().findComponentFor(event.getComponent(), target);
		String value = (String) event.getNewValue();
		if(StringUtils.isBlank(value))
			value = SystemConfig.Config.getString("onion.faces.list.size","15");
		
		data.setRows(Integer.valueOf(value));
	}
	
	public List<Integer> getSelections() {
		return this.selections;
	}

}
